import axios from 'axios'
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)
const myPlugin = (store) => {
  // 当 store 初始化后调用
  store.subscribe((mutation, state) => {
    // 每次 mutation 之后调用  // mutation 的格式为 { type, payload }
    console.log(mutation, 'mutation', state)
  })
}

export default new Vuex.Store({
  state: {
    token: '',
    movieList: [],
    total: 0,
    detailItem: {}, // 详情数据
    movieTypeArr: [],
    timeArr: [],
    copyMovieList: [],
    filterMovieTypeArr: [], // 收集过滤条件
    filterTimeArr: [], // 收集过滤条件
  },
  mutations: {
    // 数据过滤
    filter_movie_list(state, item) {
      if (item.type === 'movieType') {
        this.filterMovieTypeArr = [item]
      } else {
        this.filterTimeArr = [item]
      }
      console.log(this.filterMovieTypeArr, '-----', this.filterTimeArr)
    },
    set_token(state, token) {
      state.token = token
    },
    // 初始化数据
    set_movie_list(state, { list, total }) {
      list.forEach((item) => {
        state.movieTypeArr.push(item.movieType)
        state.timeArr.push(item.rt.slice(0, 4))
        state.movieTypeArr = [...new Set(state.movieTypeArr)]
        state.timeArr = [...new Set(state.timeArr)]
      })
      state.copyMovieList = JSON.parse(JSON.stringify(list))
      state.movieList = list
      state.total = total
    },
    // 请求数据过来之后，跟movieList中的收藏的状态做对比，然后赋值
    set_detail_item(state, item) {
      state.movieList.forEach((v) => {
        if (v.id === item.id) {
          item.collect = v.collect
        }
      })
      state.detailItem = item
    },
    set_collect_item(state) {
      state.movieList.forEach((item) => {
        if (item.id === state.detailItem.id) {
          // 首页数据
          item.collect = !item.collect
          // 详情页数据 - 并且把这个值赋值给了 详情数据
          state.detailItem.collect = !state.detailItem.collect
          // Vue.set(state.detailItem, 'collect', item.collect)
        }
      })
    },
  },
  actions: {
    async FetchMovieList({ commit }, { params }) {
      const movie = await axios.get('/api/movie', { params })
      const list = movie.data.data.list
      const total = movie.data.data.total
      commit('set_movie_list', { total, list })
      return { list }
    },
    async FetchDetail({ commit }, { detailId }) {
      const detailData = await axios.get('/api/detail', {
        params: { detailId },
      })
      console.log('detailData', detailData)
      commit('set_detail_item', detailData.data.data)
    },
  },
  plugins: [],
  getters: {},
  modules: {},
})
